package com.example.uberorganizer;

import java.text.DateFormat;  
import java.text.SimpleDateFormat;  
import java.util.ArrayList;  
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;  
import java.util.List;
import java.util.Locale;  

import android.app.Activity;  
import android.app.TimePickerDialog;
import android.app.AlertDialog;
import android.app.Dialog;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentTransaction;
import android.content.DialogInterface;
import android.graphics.Color;  
import android.os.Bundle;  
import android.os.Handler;  
import android.support.v4.app.FragmentActivity;
import android.util.Log;  
import android.view.LayoutInflater;
import android.view.View;  
import android.view.View.OnClickListener;  
import android.view.View.OnLongClickListener;
import android.widget.AdapterView;  
import android.widget.AdapterView.OnItemClickListener;  
import android.widget.ArrayAdapter;
import android.widget.GridView;  
import android.widget.LinearLayout;  
import android.widget.ListView;
import android.widget.RelativeLayout;  
import android.widget.TextView;  
import android.widget.TimePicker;
import android.widget.Toast;  


//--------------------------------------------------
// Okno interfejsu 1szego
//--------------------------------------------------

//Activity z interfejsem kalendarza 1
public class UserInterfaceOne extends FragmentActivity {

	public UserInterfaceOne handle = this;
	//zmienne
	public GregorianCalendar month, itemmonth;
	public CalendarAdapter adapter;// adapter instance  
	 public Handler handler;// for grabbing some event values for showing the dot  
	 public ArrayList<String> items; // container to store calendar items which  
	 ArrayList<String> event;  
	 LinearLayout rLayout;  
	 ArrayList<String> date;  
	 ArrayList<String> desc;  
	 static long millis;
	 static int[] myDate = new int[3];
	 int currentPosition;
	 private ListView mainListView;  
	 private ArrayAdapter<String> listAdapter;  
	 
	 class EventDesc
	 {
	     public String name; 
	     public String description;  
	     public Date date; 
	     EventDesc()
	     {
	    	 
	     }
	  };

	 // Wywolane na stworzeniu widoku
	@Override
	public void onCreate(Bundle savedInstanceState) {
		  super.onCreate(savedInstanceState);  
		  
		  // ustawiamy layout do naszego activity
		  setContentView(R.layout.calendar);  
		  Locale.setDefault(Locale.US);  
		  
		  mainListView = (ListView) findViewById( R.id.mainListView );   
		  rLayout = (LinearLayout) findViewById(R.id.text);  
		  month = (GregorianCalendar) GregorianCalendar.getInstance();  
		  itemmonth = (GregorianCalendar) month.clone();  
		  
		  items = new ArrayList<String>();  
		  
		  adapter = new CalendarAdapter(this, month);  
		  
		  GridView gridview = (GridView) findViewById(R.id.gridview);  
		  gridview.setAdapter(adapter);  
		  
		  handler = new Handler();  
		  handler.post(calendarUpdater);  
		  
		  TextView title = (TextView) findViewById(R.id.title);  
		  title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));  
		  
		  
		  //odswiezanie kalendarza na wcisnieciu dla przesuniecia kalendarza o miesiac w tyl
		  RelativeLayout previous = (RelativeLayout) findViewById(R.id.previous);  
		  previous.setOnClickListener(new OnClickListener() {  
		  
		   @Override  
		   public void onClick(View v) {  
		    setPreviousMonth();  
		    refreshCalendar();  
		  
		   }  
		  });  
		  
		//odswiezanie kalendarza na wcisnieciu dla przesuniecia kalendarza o miesiac w przod
		  RelativeLayout next = (RelativeLayout) findViewById(R.id.next);  
		  next.setOnClickListener(new OnClickListener() {  
		  
		   @Override  
		   public void onClick(View v) {  
		    setNextMonth();  
		    refreshCalendar();  
		  
		   }  
		  });  
		  
		  
		  // Funkcja podpieta do wciskania poszczegolnych dni
		  gridview.setOnItemClickListener(new OnItemClickListener() {  
		   public void onItemClick(AdapterView parent, View v,  
		     int position, long id) {  
			   currentPosition = position;
		    // usuwanie poprzedniego widoku jesli dodane
		    if (((LinearLayout) rLayout).getChildCount() > 0) {  
		     ((LinearLayout) rLayout).removeAllViews();  
		    }  
		    desc = new ArrayList<String>();  
		    date = new ArrayList<String>();  
		    ((CalendarAdapter) parent.getAdapter()).setSelected(v);  
		    String selectedGridDate = CalendarAdapter.dayString  
		      .get(position);  
		    String[] separatedTime = selectedGridDate.split("-");  
		    String gridvalueString = separatedTime[2].replaceFirst("^0*",  
		      "");// bierzemy ostatnia czesc daty (dni)
		    int gridvalue = Integer.parseInt(gridvalueString);  
		    // nastepny albo poprzedni miesiac jesli wcisniemy dni spoza biezacego miesiaca
		    if ((gridvalue > 10) && (position < 8)) {  
		     setPreviousMonth();  
		     refreshCalendar();  
		    } else if ((gridvalue < 7) && (position > 28)) {  
		     setNextMonth();  
		     refreshCalendar();  
		    }  
		    ((CalendarAdapter) parent.getAdapter()).setSelected(v);  
		  
		    for (int i = 0; i < Utility.startDates.size(); i++) {  
		     if (Utility.startDates.get(i).equals(selectedGridDate)) {  
		      desc.add(Utility.nameOfEvent.get(i));  
		     }  
		    }  
		  
		    if (desc.size() > 0) {  
		     for (int i = 0; i < desc.size(); i++) {  
		      TextView rowTextView = new TextView(UserInterfaceOne.this);  
		  
		      // set some properties of rowTextView or something  
		      rowTextView.setText("Event:" + desc.get(i));  
		      rowTextView.setTextColor(Color.BLACK);  
		  
		      // add the textview to the linearlayout  
		      rLayout.addView(rowTextView);  
		  
		     }  
		  
		    }  
		  
		    desc = null;  
		   }  
		  
		 
		   
		  });  
		  
		  //Na dlugim wcisnieciu dnia
		  gridview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				currentPosition = position;
				FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
				EventDialog dial = new EventDialog(); // klasa odpowiedzialna za okienko dodawania wydarzen
				((CalendarAdapter) parent.getAdapter()).setSelected(view);  // zaznaczamy dzien ktory wcisnelismy
				String selectedGridDate = CalendarAdapter.dayString.get(position);  // pobieramy biezaca date
				String[] separatedTime = selectedGridDate.split("-");  // rozdzielamy usuwajac '-'

			    myDate[0]=Integer.parseInt(separatedTime[0]); // rok
			    myDate[1]=Integer.parseInt(separatedTime[1]); // miesiac
			    myDate[2]=Integer.parseInt(separatedTime[2]); // dzien
				dial.show(ft, "addevent");
				return true;
			}
			
		});
		 }  
	
	
	public void showEventDialog(View v)
	{
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		EventDialog dial = new EventDialog(); // klasa odpowiedzialna za okienko dodawania wydarzen
		String selectedGridDate = CalendarAdapter.dayString.get(currentPosition);  // pobieramy biezaca date
		String[] separatedTime = selectedGridDate.split("-");  // rozdzielamy usuwajac '-'

	    myDate[0]=Integer.parseInt(separatedTime[0]); // rok
	    myDate[1]=Integer.parseInt(separatedTime[1]); // miesiac
	    myDate[2]=Integer.parseInt(separatedTime[2]); // dzien
		dial.show(ft, "addevent");
	}
	// funkcja do wybierania godziny
	public void showTimePickerDialog(View v) {
		TimePickerFragment newFragment = new TimePickerFragment();
	    newFragment.show(getSupportFragmentManager(), "timePicker");
	}
	
	// funkcja do wybierania godziny
	public void showTimePickerDialogEnd(View v) {
		TimePickerFragmentEnd newFragment = new TimePickerFragmentEnd();
	    newFragment.show(getSupportFragmentManager(), "timePicker");
	}
	
	// przechodzenie do nastepnego miesiaca
	 protected void setNextMonth() {  
		  if (month.get(GregorianCalendar.MONTH) == month  
		    .getActualMaximum(GregorianCalendar.MONTH)) {  
		   month.set((month.get(GregorianCalendar.YEAR) + 1),  
		     month.getActualMinimum(GregorianCalendar.MONTH), 1);  
		  } else {  
		   month.set(GregorianCalendar.MONTH,  
		     month.get(GregorianCalendar.MONTH) + 1);  
		  }  
		  
		 }  
		  
	 
	 // przechodzenie do poprzedniego miesiaca
		 protected void setPreviousMonth() {  
		  if (month.get(GregorianCalendar.MONTH) == month  
		    .getActualMinimum(GregorianCalendar.MONTH)) {  
		   month.set((month.get(GregorianCalendar.YEAR) - 1),  
		     month.getActualMaximum(GregorianCalendar.MONTH), 1);  
		  } else {  
		   month.set(GregorianCalendar.MONTH,  
		     month.get(GregorianCalendar.MONTH) - 1);  
		  }  
		  
		 }  
		  
		 // odswiezenie kalendarza
		 public void refreshCalendar() {  
		  TextView title = (TextView) findViewById(R.id.title);  
		  
		  adapter.refreshDays();  
		  adapter.notifyDataSetChanged();  
		  handler.post(calendarUpdater); // generate some calendar items  
		  
		  title.setText(android.text.format.DateFormat.format("MMMM yyyy", month));  
		 }  
		 
		 // watek odswiezajacy kalendarz
	 public Runnable calendarUpdater = new Runnable() {  
		  
		  @Override  
		  public void run() {  
		   items.clear();  
		  
		   // Print dates of the current week  
		   DateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);  
		   String itemvalue;  
		   event = Utility.readCalendarEvent(UserInterfaceOne.this);  
		   listAdapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.simplerow,(List<String>)event);  
		   mainListView.setAdapter( listAdapter ); 
		  // System.out.println(event);
		   for (int i = 0; i < Utility.startDates.size(); i++) {  
		    itemvalue = df.format(itemmonth.getTime());  
		    itemmonth.add(GregorianCalendar.DATE, 1);  
		    items.add(Utility.startDates.get(i).toString());  
		   }  
		   adapter.setItems(items);  
		   adapter.notifyDataSetChanged();  
		  }  
		 };  
		 
		 
		 
		//klasa odpowiedzialna za pobieranie czasu
		public static class TimePickerFragment extends DialogFragment
		         implements TimePickerDialog.OnTimeSetListener 
		         {
			TextView t;
			@Override
			public Dialog onCreateDialog(Bundle savedInstanceState) 
			{
			// Use the current time as the default values for the picker
			final Calendar c = Calendar.getInstance();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);
			
			
			// Create a new instance of TimePickerDialog and return it
			return new TimePickerDialog(getActivity(), this, hour, minute,
					 android.text.format.DateFormat.is24HourFormat(getActivity()));
			}
			
			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
				// na ustawieniu godziny tworzymy pelna date
			    Calendar start = Calendar.getInstance();
			    start.set(myDate[0], myDate[1]-1,myDate[2], hourOfDay, minute, 0);
			
			    //wstawiamy ja w milisekundach do zmiennej
				EventDialog.startTime = start.getTimeInMillis(); 
				// wypisujemy na naszym okienku dodajacym zdarzenie
				EventDialog.t1.setText(Integer.toString(hourOfDay)+':'+Integer.toString(minute));
				
			}
		}


		public static class TimePickerFragmentEnd extends DialogFragment
		implements TimePickerDialog.OnTimeSetListener {
		
			@Override
			public Dialog onCreateDialog(Bundle savedInstanceState) {
			//Use the current time as the default values for the picker
			final Calendar c = Calendar.getInstance();
			int hour = c.get(Calendar.HOUR_OF_DAY);
			int minute = c.get(Calendar.MINUTE);
			
			//Create a new instance of TimePickerDialog and return it
			return new TimePickerDialog(getActivity(), this, hour, minute,
			android.text.format.DateFormat.is24HourFormat(getActivity()));
			}
			
			@Override
			public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
			{
				// na ustawieniu godziny tworzymy pelna date
			    Calendar start = Calendar.getInstance();
			    start.set(myDate[0], myDate[1],myDate[2], hourOfDay, minute, 0);
			  //wstawiamy ja w milisekundach do zmiennej
				EventDialog.endTime = start.getTimeInMillis(); 
				// wypisujemy na naszym okienku dodajacym zdarzenie
			EventDialog.t2.setText(Integer.toString(hourOfDay)+':'+Integer.toString(minute));
			}
		}
		
		public void Reload()
		{
			finish();
			startActivity(getIntent());
		}

}


